package com.hulman.oms.service;

import com.hulman.oms.bean.ElectricMeter;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.WaterMeter;
import com.hulman.oms.dao.WaterMeterDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class WaterMeterService
{
    @Autowired
    private WaterMeterDao waterMeterDao;

    public List<WaterMeter> findWaterMeters(Map<String, Object> map)
    {
        return waterMeterDao.findWaterMeters(map);
    }

    public Integer findWaterMetersCount(Map<String, Object> map)
    {
        return waterMeterDao.findWaterMetersCount(map);
    }


    public List<WaterMeter> findAllWaterMeters()
    {
        Map<String,Object> map = new HashMap<>();
        return waterMeterDao.findWaterMeters(map);
    }

    public Result findWaterMetersResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = waterMeterDao.findWaterMetersCount(map);
        List<WaterMeter> data = waterMeterDao.findWaterMeters(map);
        return new Result(data, count);
    }

    public WaterMeter findWaterMeterById(Integer id)
    {
        return waterMeterDao.findWaterMeterById(id);
    }

    public void saveWaterMeter(WaterMeter waterMeter)
    {
        if (waterMeter.getRatio() == null)
        {
            waterMeter.setRatio(WaterMeter.DEFAULT_RATIO);
        }
        if (waterMeter.getId() != null && waterMeter.getId() != 0)
        {
            waterMeterDao.updateWaterMeter(waterMeter);
        } else
        {
            waterMeterDao.insertWaterMeter(waterMeter);
        }
    }

    public void deleteWaterMeterById(Integer id)
    {
        waterMeterDao.deleteWaterMeterById(id);
    }

    public void deleteWaterMeters(int[] ids)
    {
        waterMeterDao.deleteWaterMeters(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importWaterMeters(List<WaterMeter> meters)
    {
        for (WaterMeter meter : meters)
        {
            saveWaterMeter(meter);
        }
    }

}
